/**
 * @通用列表
 * 工单列表
 */
import { addRule, removeRule, rule, updateRule, getPatientList, getDeptList, setPatientList, delPatientList, } from '@/services/ant-design-pro/api';
import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns, ProDescriptionsItemProps } from '@ant-design/pro-components';
import {
  FooterToolbar,
  ModalForm,
  PageContainer,
  ProDescriptions,
  ProFormText,
  ProFormTextArea,
  ProTable,
} from '@ant-design/pro-components';
import { FormattedMessage, useIntl } from '@umijs/max';
import { Button, Drawer, Input, message, Table, Form, Row, Col, DatePicker, Modal, Select, InputNumber, Popconfirm, Radio, } from 'antd';
import React, { useRef, useState, useEffect, } from 'react';
import type { FormValueType } from './components/UpdateForm';
import UpdateForm from './components/UpdateForm';
import moment from 'moment';
import { cloneDeep } from 'lodash';
const { RangePicker } = DatePicker;
const { TextArea } = Input;


const TableList: React.FC = () => {
  const [dataSource, setDataSource] = useState<any[]>([]);
  const [form] = Form.useForm();
  const [modalVisible, setModalVisible] = useState(false);
  const [modalType, setModalType] = useState("see");
  const [getParams, setGetParams] = useState({
    name: "", MachineSN: "",
    deptId: "",
    admitTimeStart: moment().startOf('month').format('YYYY-MM-DD'),
    admitTimeEnd: moment().endOf('month').format('YYYY-MM-DD'),
  });
  const [deptList, setDeptList] = useState([]); //部门



  useEffect(() => {
    console.log('初始化加载0')
    getDeptListApi()
    getPatientListOnClick()
  }, [])
  // 获取部门
  const getDeptListApi = () => {
    getDeptList({
      username: localStorage.getItem("username") || "",
    }).then((res: any) => {
      setDeptList(res.data)
    })
  }
  // 保存 新增 编辑 确定
  const onFinish = (values: any) => {
    console.log(values, 'values')
    setPatientList(values).then((res: any) => {
      if (res.success) {
        message.success(modalType == "add" ? "新增成功！" : modalType == "edit" ? "编辑成功！" : "操作成功！")
        getPatientListOnClick()
        handleCancel()
      }
    })
  }
  const handleOk = () => {
    form.validateFields().then((values) => {
      onFinish(values);
    })
  }
  const handleCancel = () => {
    setModalVisible(false)
    form.resetFields()
  }
  const getChange = (type: any, values: any) => {
    console.log(values, 'values')
    let getParamsNew: any = cloneDeep(getParams)
    if (type == "name" || type == "MachineSN") {
      getParamsNew[type] = values.target.value
    } else if (type == "deptId") {
      getParamsNew[type] = values
    } else if (type == "admitTime" && Array.isArray(values) && values.length > 1) {
      getParamsNew["admitTimeStart"] = moment(values[0]).format('YYYY-MM-DD')
      getParamsNew["admitTimeEnd"] = moment(values[1]).format('YYYY-MM-DD')
    }
    setGetParams({ ...getParamsNew, })
  }
  // 列表查询
  const getPatientListOnClick = () => {
    console.log(getParams, 'getParams')
    getPatientList(getParams).then((res: any) => {
      setDataSource(res.data)
    })
  }
  // 删除病人
  const deletePatient = (record: any) => {
    if (!record.MachineSN) {
      message.warning("当前机器sn异常!")
      return
    }
    delPatientList({ MachineSN: record.MachineSN }).then((res: any) => {
      if (res.success) {
        message.success("删除成功！")
        getPatientListOnClick()
      }
    })
  }
  const changeModal = (type: string, record: any) => {
    setModalVisible(true)
    setModalType(type)
    console.log(record, 'record')
    form.setFieldsValue({
      ...record,
      admitTime: record.admitTime ? moment(record.admitTime) : null,
      birthdate: record.birthdate ? moment(record.birthdate) : null,
    });
    return
    if (type == "add") {
      form.setFieldsValue(record);
    } else if (type == "edit") {
      form.setFieldsValue(record);
    }
  }

  const columns: any = [
    {
      title: "客户名称",
      dataIndex: 'ptName',
    }, {
      title: "机器型号",
      dataIndex: 'ModelNo',
    }, {
      title: "机器sn",
      dataIndex: 'MachineSN',
    }, {
      title: "报修日期",
      dataIndex: 'admitTime',
    }, {
      title: '部门',
      dataIndex: 'deptId',
      render: (text: any, record: object) => {
        return (
          <div>
            {Array.isArray(deptList) && deptList.length > 2 && deptList[text - 1]?.deptName}
          </div>
        )
      }
    }, {
      title: '操作',
      dataIndex: '',
      align: 'center',
      render: (text: any, record: object) => (
        <div>
          <Button type="primary" onClick={() => changeModal("edit", record)}>编辑</Button>
          <Popconfirm
            title="确认删除该病人?"
            onConfirm={() => deletePatient(record)}
            okText="确认"
            cancelText="取消"
          >
            <Button style={{ backgroundColor: 'red', color: 'white', borderColor: 'red', marginLeft: 10 }}>删除</Button>
          </Popconfirm>
        </div>
      )
    },
  ];
  // PageContainer
  return (
    <>
      <div>
        <Row>
          <Col span={4}>
            <Form.Item label="客户名称" labelCol={{ span: 10 }} wrapperCol={{ span: 13 }}>
              <Input placeholder='请输入客户名称' onChange={(e) => getChange("name", e)} value={getParams.name} />
            </Form.Item>
          </Col>
          <Col span={4}>
            <Form.Item label="机器sn" labelCol={{ span: 8 }} wrapperCol={{ span: 15 }}>
              <Input placeholder='请输入' onChange={(e) => getChange("MachineSN", e)} value={getParams.MachineSN} />
            </Form.Item>
          </Col>
          <Col span={4}>
            <Form.Item label="部门" labelCol={{ span: 8 }} wrapperCol={{ span: 15 }}>
              <Select
                placeholder='请选择部门'
                onChange={(e) => getChange("deptId", e)} value={getParams.deptId}
              >
                <Option value={""}>全部</Option>
                {Array.isArray(deptList) && deptList.map((item: any) => {
                  return <Option value={item.deptId}>{item.deptName}</Option>
                })}

              </Select>
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item label="报修日期" labelCol={{ span: 8 }} wrapperCol={{ span: 15 }}>
              <RangePicker onChange={(e) => getChange("admitTime", e)}
                allowClear={false}
                value={[
                  getParams.admitTimeStart ? moment(getParams.admitTimeStart) : null,
                  getParams.admitTimeEnd ? moment(getParams.admitTimeEnd) : null
                ]} />
            </Form.Item>
          </Col>
          <Col span={4} style={{ position: 'relative' }}>
            <Form.Item style={{ position: 'absolute', right: 0, width: '100%' }} wrapperCol={{ span: 24 }}>
              <Button type="primary" style={{ marginRight: 10 }} onClick={getPatientListOnClick}>查询</Button>
              <Button type="primary" onClick={() => changeModal("add", {})}>新增</Button>
            </Form.Item>
          </Col>
        </Row>

      </div>
      <Table dataSource={dataSource} columns={columns} />

      <Modal
        title={`${modalType == "add" ? "新增" : modalType == "edit" ? "编辑" : ""}工单`}
        visible={modalVisible} onOk={handleOk} onCancel={handleCancel}
        width={"800px"}
      >
        <Form
          form={form}
          labelCol={{ span: 6 }}
          wrapperCol={{ span: 16 }}
          layout="horizontal"
          onFinish={onFinish}
          style={{ height: 'calc(60vh)', overflowY: 'auto', }}
        >
          <div style={{ width: '100%' }}>
            <Row style={{ border: '1px solid #D9D9D9', borderRadius: 5 }}>
              <Col span={2} style={{ position: 'relative' }}>
                <div style={{
                  writingMode: 'vertical-rl',
                  position: 'absolute',
                  top: "38%",
                  left: "38%",
                }}>用户信息</div>
              </Col>
              <Col span={22} style={{ borderLeft: '1px solid #D9D9D9', paddingTop: 5 }}>
                <Row>
                  <Col span={12}>
                    <Form.Item
                      label="客户名称" name="ptName"
                      rules={[{
                        required: true,
                        message: '请输入客户名称!'
                      }]}>
                      <Input placeholder='请输入客户名称' />
                    </Form.Item>
                  </Col>
                  <Col span={12}>
                    <Form.Item label="报修日期" name="admitTime">
                      <DatePicker />
                    </Form.Item>
                  </Col>
                </Row>
                <Row>
                  <Col span={12}>
                    <Form.Item label="联系人" name="contacts">
                      <Input placeholder='请输入' />
                    </Form.Item>
                  </Col>
                  <Col span={12}>
                    <Form.Item label="联系电话" name="contactNumber"
                      rules={[{
                        required: true,
                        message: '请输入联系电话!'
                      }]}
                    >
                      <Input placeholder='请输入联系电话' />
                    </Form.Item>
                  </Col>
                </Row>
                <Row>
                  <Col span={12}>
                    <Form.Item label="客户地址" name="customerAddress">
                      <TextArea placeholder='请输入' />
                    </Form.Item>
                  </Col>
                </Row>
                <Row>
                  <Col span={12}>
                    <Form.Item label="反应问题" name="transportReactionProblem">
                      <TextArea placeholder='请输入' />
                    </Form.Item>
                  </Col>
                </Row>
              </Col>
            </Row>
            <Row style={{ border: '1px solid #D9D9D9', marginTop: 5, borderRadius: 5 }}>
              <Col span={2} style={{ position: 'relative' }}>
                <div style={{
                  writingMode: 'vertical-rl',
                  position: 'absolute',
                  top: "38%",
                  left: "38%",
                }}>产品信息</div>
              </Col>
              <Col span={22} style={{ borderLeft: '1px solid #D9D9D9', paddingTop: 5 }}>
                <Row>
                  <Col span={12}>
                    <Form.Item label="机器型号" name="ModelNo">
                      <Input placeholder='请输入' />
                    </Form.Item>
                  </Col>
                </Row>
                <Row>
                  <Col span={12}>
                    <Form.Item label="部门" name="deptId" rules={[{
                      required: true,
                      message: '请选择部门!'
                    }]}>
                      <Select
                        placeholder='请选择部门'
                        onChange={(e) => getChange("deptId", e)} value={getParams.deptId}
                      >
                        {Array.isArray(deptList) && deptList.map((item: any) => {
                          return <Option value={item.deptId}>{item.deptName}</Option>
                        })}

                      </Select>
                    </Form.Item>
                  </Col>
                </Row>
                <Row>
                  <Col span={12}>
                    <Form.Item label="机器sn" name="MachineSN"
                      rules={[{
                        required: true,
                        message: '请输入客户名称!'
                      }]}>
                      <Input placeholder='请输入' />
                    </Form.Item>
                  </Col>
                </Row>
                <Row>
                  <Col span={12}>
                    <Form.Item label="紧急情况" name="emergency">
                      <Radio.Group >
                        <Radio value={"紧急"}>紧急</Radio>
                        <Radio value={"一般"}>一般</Radio>
                        <Radio value={"轻微"}>轻微</Radio>
                      </Radio.Group>
                    </Form.Item>
                  </Col>
                </Row>
                <Row>
                  <Col span={12}>
                    <Form.Item label="问题类型" name="questionType">
                      <Radio.Group >
                        <Radio value={"硬件问题"}>硬件问题</Radio>
                        <Radio value={"软件问题"}>软件问题</Radio>
                      </Radio.Group>
                    </Form.Item>
                  </Col>
                </Row>
              </Col>
            </Row>
            <Row style={{ marginTop: 5, paddingTop: 5 }}>
              <Col span={2}></Col>
              <Col span={22}>
                <Col span={12}>
                  <Form.Item label="备注" name="notes">
                    <TextArea placeholder='请输入' />
                  </Form.Item>
                </Col>
              </Col>
            </Row>
          </div>
        </Form >
      </Modal>
    </>
  );
};

export default TableList;

